# -*- coding: utf-8 -*-
from datetime import datetime
from storm.locals import *
from accost.utils import *
from accost import *
from ${project_name} import store 


class User(Storm):
    __storm_table__ = "user"
    id              = Int(primary=True)
    username        = Unicode()                             # 用户名，可以为中文
    password        = Unicode()                             # 密码，sha1加密
    last_login      = DateTime(default_factory=datetime.now)# 上次登录时间
    date_joined     = DateTime(default_factory=datetime.now)# 加入日期
    is_admin        = Bool(default=False)                   # 是否为管理员
    content         = Unicode(default=u'')                  # 用户提供的内容

    @classmethod
    def hasUser(cls, username):
        return bool(store.find(User,
                User.username == username
            ).count())

    def login(self, request):
        """用户登录"""
        request.user = self
        self.last_login = datetime.now()
        store.add(self)
        store.commit()
        request.session[SESSION_USER_KEY] = self.id

    def setPassword(self, raw_password):
        """设置用户密码"""
        self.password = get_encrypt_password(raw_password)

    def checkPassword(self, raw_password):
        """检查密码与用户密码是否匹配
        Returns a boolean of whether the raw_password was correct. Handles
        encryption formats behind the scenes.
        """
        return check_password(raw_password, self.password)
        # Backwards-compatibility check. Older passwords won't include the
        # algorithm or salt.
        if '$' not in self.password:
            is_correct = (self.password == get_hexdigest('md5', '', raw_password))
            if is_correct:
                # Convert the password to the new, more secure format.
                self.setPassword(raw_password)
                store.add(self)
                store.commit()
            return is_correct
        else:
            return check_password(raw_password, self.password)

